package cc.lj.internal.mobilepay.application.service;

import cc.lj.internal.core.exception.ServiceException;
import cc.lj.internal.core.utils.EntityMapTransUtils;
import cc.lj.internal.mobilepay.domain.model.vo.CiticLogDO;
import cc.lj.internal.mobilepay.infrastructure.excepion.MobilepayExceptionEnum;
import cc.lj.internal.mobilepay.interfaces.dto.NativeResponseDTO;
import cc.lj.internal.mobilepay.interfaces.dto.command.NativeCommand;
import lj.internal.dict.enums.EnumCiticApiType;
import lj.internal.dict.enums.EnumCiticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一下单订单 app service
 * @author liangxifeng
 * @date 2022/11/30 15:38
 */
@Service
@Slf4j
public class NativeAppService extends CiticAppService<NativeCommand, NativeResponseDTO> {

    /**
     *
     * 1.从外部接收的参数
     * 2.新增中信日志表数据
     * 3. 调用中信统一下单接口
     * 4. 将响应日志修改到数据中
     * @param command
     * @return
     */
    @Override
    public NativeResponseDTO doMain(NativeCommand command) {
        Map<String,String> reqMap = new HashMap<>();
        //1.从外部接收的参数
        reqMap.put("out_trade_no",command.getOutTradeNo()); //商户订单号
        reqMap.put("total_fee",command.getTotalFee().toString()); //交易金额
        //该接口其他必要参数
        reqMap.put("service", EnumCiticService.NATIVE.getCode());//交易类型
        reqMap.put("mch_id", ljConfig.getMchId()); //商户号
        reqMap.put("mch_create_ip",ljConfig.getOutIp()); //上传商户真实的发起交易的终端出网IP
        reqMap.put("terminal_info",createTerminalInfo());//终端信息，经纬度等等
        //通知地址
        reqMap.put("notify_url",command.getNotifyUrl() != null ? command.getNotifyUrl() : ljConfig.getNotifyURL());
        //商品描述
        reqMap.put("body",command.getBody() != null ? command.getBody() : ljConfig.getProDesc());

        //订单生成时间与超时时间需要同时传入才会生效
        boolean timeOne = command.getTimeStart() != null && command.getTimeExpire() == null;
        boolean timeTwo = command.getTimeStart() == null && command.getTimeExpire() != null;
        if(timeOne || timeTwo) {
            throw new ServiceException(MobilepayExceptionEnum.CITIC_NATIVE_TIME_FAILED);
        }

        if(command.getTimeStart() != null && command.getTimeExpire() != null) {
            reqMap.put("time_start",command.getTimeStart());
            reqMap.put("time_expire",command.getTimeExpire());
        }
        //附加数据,中信回调时，传回
        if(command.getAttach() != null) {
            reqMap.put("attach",command.getAttach());
        }

        /**
         * 2.新增中信日志表数据
         */
        CiticLogDO addLogDO = new CiticLogDO();
        addLogDO.setTotalFee(command.getTotalFee());//交易金额
        addLogDO.setApiType(EnumCiticApiType.NATIVE.getCode()); //接口类型
        Integer lastId = citicLog.addLog(command,reqMap,addLogDO);

        /**
         * 3. 调用中信统一撤销接口
         */
        Map<String, String> resMap = reuqestCitic.request(reqMap);

        /**
         * 4. 将响应日志修改到数据中
         */
        CiticLogDO updateLogDo = new CiticLogDO();
        if(resMap.get("code_url") != null) { //二维码链接地址
            updateLogDo.setCodeUrl(resMap.get("code_url"));
        }
        if(resMap.get("trade_type") != null) {//交易类型
            updateLogDo.setTradeType(resMap.get("trade_type"));
        }
        //updateLogDo.setCo 这里需要添加url地址
        citicLog.updateLog(lastId,resMap,updateLogDo);

        //通信状态
        boolean returnCodeBool = resMap.get("return_code") != null && resMap.get("return_code").equalsIgnoreCase("SUCCESS");
        //业务状态
        boolean resultCodeBool = resMap.get("result_code") != null && resMap.get("result_code").equalsIgnoreCase("SUCCESS");
        //boolean resultRes = resMap.get("return_code") != null && resMap.get("return_code").equalsIgnoreCase("SUCCESS")  && resMap.get("result_code ") != null && resMap.get("result_code").equalsIgnoreCase("SUCCESS");
        boolean resultRes = returnCodeBool && resultCodeBool;
        //通信状态和业务结果都为 SUCCESS
        resMap.remove("sign"); //签名信息太长，可读性太差，这里删除掉了
        if( resultRes ) {
            log.info("pact_id:"+command.getPactId()+",商户订单号:"+command.getOutTradeNo()+",统一下单成功，结果map="+resMap);
            NativeResponseDTO responseDTO = EntityMapTransUtils.mapToEntity1(NativeResponseDTO.class, resMap);
            return responseDTO;
        } else {
            log.error("pact_id:"+command.getPactId()+",商户订单号:"+command.getOutTradeNo()+",统一下单失败，结果map="+resMap);
            //接口调用失败
            throw new ServiceException(MobilepayExceptionEnum.CITIC_NATIVE_FAILED,resMap.toString());
        }
    }
}
